package com.raidpoints.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.SelectionCell;
import com.google.gwt.cell.client.TextInputCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasMouseDownHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.view.client.ListDataProvider;
import com.raidpoints.client.RaidPoints.AuthType;

public class PointsPage extends Composite{
	RaidPoints rp;
	PointsPage mpp;
	HorizontalPanel signuppan;
	ArrayList<Widget> adminwidgets;	
	ArrayList<character> charlist;
	ArrayList<pointsevent> pointslist;
	ToggleButton editButton;
	HashMap<pointsevent,pointsrow> rl;
	MyFlexTable chardisplay;
	FlexTable pointsdisplay;
	event evt;
	MultiWordSuggestOracle oracle;
	HorizontalPanel pointsPan;
	String lastboss;
	NCDate lastts;
	TextBox signupBox;
	boolean currcolor;
	boolean tlock;
	//	CellTable<pointsevent> lootTable;
	//	ListDataProvider<pointsevent> lootProvider;
	//	Column<pointsevent,String> timeCol;
	//	TextColumn<pointsevent> timeColNE;
	//	Column<pointsevent,String> nameCol;
	//	TextColumn<pointsevent> nameColNE;
	RaidPoints.AuthType lastatype;
	//	Column<pointsevent,String> encounterCol;
	//	Column<pointsevent,String> characterCol;
	//	Column<pointsevent,String> changetypeCol;
	HashMap<String,ArrayList<String[]>> bossloot;
	AsyncCallback<ArrayList<character>> charCallback;
	AsyncCallback<HashMap<String,ArrayList<String[]>>> bossCallback;
	Comparator<pointsevent> peComp;
	DockLayoutPanel dpan;
	TextBox startBox, endBox, wwsBox;
	Label startLabel,endLabel, timeLabel, wwsELabel;
	HTML wwsLabel;
	Button refreshButton;
	ArrayList<String> bosssort;
	Button slotButton;
	Button signupButton;
	Button viewButton;
	Button modButton;
	boolean viewSlot;
	boolean isCL;
	ArrayList<String> roles;
	HashMap<String,Integer> rolemap;
	HashMap<String,character> cmap;
	String mychar;
	ScrollPanel chatScroll;
	HTML chatArea;
	TextBox messageBox;
	Button sendButton;
	VerticalPanel chatPanel;
	ArrayList<String> bids;

	PointsPage(RaidPoints mrp,event mevt){
		mpp = this;
		lastatype = AuthType.noauth;
		charlist = new ArrayList<character>();
		pointslist = new ArrayList<pointsevent>();
		bossloot = null;
		currcolor = false;
		tlock = false;
		mychar = "";
		isCL = false;
		roles = new ArrayList<String>();
		rolemap = new HashMap<String,Integer>();
		cmap = new HashMap<String,character>();
		viewSlot = false;
		rl = new HashMap<pointsevent,pointsrow>();
		bosssort = new ArrayList<String>();
		oracle = new MultiWordSuggestOracle();
		rp = mrp;
		evt=mevt;
		adminwidgets = new ArrayList<Widget>();
		dpan = new DockLayoutPanel(Unit.EM);
		timeLabel = new Label();
		initWidget(dpan);
		lastboss = "";

		peComp = new Comparator<pointsevent>(){
			@Override
			public int compare(pointsevent arg0, pointsevent arg1) {
				return arg0.ts.compareTo(arg1.ts);
			}
		};

		HorizontalPanel signuppan = new HorizontalPanel();
		refreshButton = new Button("Refresh");
		editButton = new ToggleButton("Edit");
		modButton = new Button("Modify Event");
		signupButton = new Button("Sign Up");
		viewButton = new Button("Slot View");
		signupBox = new TextBox();
		Button addRaiderButton = new Button("Add Chars");
		Button removeRaiderButton = new Button("Remove Chars");
		slotButton = new Button("Slot");
		signuppan.add(editButton); signuppan.add(refreshButton); signuppan.add(modButton); signuppan.add(viewButton); if(!evt.over) signuppan.add(signupButton); signuppan.add(signupBox); signuppan.add(addRaiderButton); signuppan.add(removeRaiderButton);
		signuppan.add(slotButton);
		adminwidgets.add(addRaiderButton); adminwidgets.add(removeRaiderButton); adminwidgets.add(signupBox); 
		dpan.addNorth(signuppan,3); editButton.setVisible(false); slotButton.setVisible(false); modButton.setVisible(false);

		refreshButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				Refresh();
			}
		});

		signupButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				EventSignupBox sb = new EventSignupBox(rp,evt,mpp);
				sb.center(); sb.show();
			}
		});

		modButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(evt.creator == 0){
					NewEventBox neb = new NewEventBox(rp,mpp,null,evt);
					neb.center(); neb.show();
				}
				else{
					NewEventBoxOther neb = new NewEventBoxOther(rp,mpp,null,evt);
					neb.center(); neb.show();
				}
			}
		});

		viewButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(viewSlot){
					viewSlot = false;
					viewButton.setText("Slot View");
				}
				else{
					viewSlot = true;
					viewButton.setText("Points View");
				}
				DrawCharList();
			}
		});

		slotButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				SlottingBox sb  = new SlottingBox(rp,evt,isCL);
				sb.setPopupPosition(Window.getClientWidth()/10,Window.getClientHeight()/10); sb.show();
				sb.GetChars();
			}
		});

		editButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(editButton.getValue()){
					timeLabel.setVisible(false);
					wwsLabel.setVisible(false);
					refreshButton.setVisible(false);
					//dpan.setWidgetSize(pointsPan, 3);
					for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(true);
					rl.clear();
					for(pointsevent p: pointslist){
						rl.put(p, new lootRow(p));
					}
					DrawPointsList();
				}
				else{
					timeLabel.setVisible(true);
					refreshButton.setVisible(true);
					wwsLabel.setVisible(true);
					//dpan.setWidgetSize(pointsPan, 0);
					for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(false);
					//					rp.rpsvc.GetEventList(pointsCallback);
					//					for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(true);
					//					for(pointsevent p: pointslist){
					//						rl.clear();
					//						rl.put(p, new lootRowNE(p));
					//					}
					GetLoot();
					GetEvent();
				}
				//	DrawPointsList();
			}
		});

		addRaiderButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(signupBox.getText().equalsIgnoreCase("")) return;
				rp.rpsvc.AddCharsToEvent(evt, signupBox.getText().replace(" ", ""), charCallback);
				signupBox.setText("");
			}
		});

		removeRaiderButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(signupBox.getText().equalsIgnoreCase("")) return;
				ArrayList<character> tcl = new ArrayList<character>();
				String[] split = signupBox.getText().replace(" ", "").split(",");
				for(int i =0; i < split.length; i++){
					for(character j : charlist){
						if(j.name.equalsIgnoreCase(split[i])){
							tcl.add(j); break;
						}
					}
				}
				rp.rpsvc.RemoveCharsFromEvent(evt, tcl, charCallback);
				signupBox.setText("");
			}
		});

		if(evt.game.equals("")){
			editButton.setVisible(false);
			signupButton.setVisible(false);
			slotButton.setVisible(false);
		}


		ScrollPanel clPan = new ScrollPanel();
		DockLayoutPanel tPanel = new DockLayoutPanel(Unit.EM);
		chatPanel = new VerticalPanel();
		DecoratorPanel decPan = new DecoratorPanel();
		//	decPan.setWidth("500px");
		chatPanel.setHeight("20em");

		chardisplay  = new MyFlexTable();
		chardisplay.addStyleName("cw-FlexTable");

		if(!evt.game.equals("")){
			clPan.add(chardisplay);
		}

		if(evt.game.equals("SWTOR") || evt.creator > 0) dpan.addNorth(tPanel,30);
		else dpan.addNorth(tPanel, 25);

		if(evt.game.equals("")){
			tPanel.add(chatPanel);
		}
		else{
			tPanel.addEast(chatPanel, 45);
			tPanel.add(clPan);
		}

		chatScroll = new ScrollPanel();
		chatArea = new HTML();
		messageBox = new TextBox();
		sendButton = new Button("Send");
		Button chatrefreshButton = new Button("Refresh");
		//chatArea.setWidth("500px");
		chatArea.setHeight("16em");
		messageBox.setWidth("370px");
		sendButton.setWidth("50px");
		chatrefreshButton.setWidth("80px");
		HorizontalPanel sendPanel = new HorizontalPanel();
		sendPanel.add(messageBox); sendPanel.add(sendButton); 
		sendPanel.add(chatrefreshButton); 
		//	decPan.add(chatScroll);
		chatScroll.add(chatArea);
		chatPanel.add(chatScroll); chatPanel.add(sendPanel);

		chatPanel.setVisible(false);

		final AsyncCallback<String> sendCallback = new AsyncCallback<String>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(String result) {
				rp.PollChat();
				if(result == null) return;
				else if(result.equals("cleared")) GetChat();
				else AddMessage(result);
			}

		};

		sendButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(messageBox.getText().equals("")) return;
				if(mychar.equals("")) GetMyChar();
				rp.rpsvc.SendChatMessage(messageBox.getText(), mychar, evt, sendCallback);
				if(messageBox.getText().startsWith("/roll") || messageBox.getText().startsWith("/random") || messageBox.getText().startsWith("/start")){
					if(!tlock){
						Timer t = new Timer(){
							int c = 0;
							@Override
							public void run() {
								c++;
								rp.PollChat();
								if(c>25){
									tlock = false;
									this.cancel();
								}
							}	
						};
						tlock = true;
						t.scheduleRepeating(2000);
					}
				}
				messageBox.setText("");
			}
		});

		chatrefreshButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				GetChat();
				if(!tlock){
					Timer t = new Timer(){
						int c = 0;
						@Override
						public void run() {
							c++;
							rp.PollChat();
							if(c>10) {
								tlock = false;
								this.cancel();
							}
						}	
					};
					tlock = true;
					t.scheduleRepeating(2000);
				}
			}
		});

		messageBox.addKeyPressHandler(new KeyPressHandler(){
			public void onKeyPress(KeyPressEvent event) {
				if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
					sendButton.click();
				}
			}
		});

		pointsPan = new HorizontalPanel();
		final Button newEventButton = new Button("New Event");
		Button prevEventButton = new Button("Add loot to previous");
		final Button updateButton = new Button("Update");
		startBox = new TextBox(); endBox = new TextBox();
		startBox.setMaxLength(5); endBox.setMaxLength(5);
		startBox.setWidth("55px"); endBox.setWidth("55px");
		startLabel = new Label("Raid Start:"); endLabel = new Label("Raid End:");
		wwsELabel = new Label("Raid Stats:");
		wwsBox = new TextBox();
		wwsLabel = new HTML();
		adminwidgets.add(newEventButton); adminwidgets.add(prevEventButton); adminwidgets.add(updateButton);
		adminwidgets.add(startBox); adminwidgets.add(startLabel); adminwidgets.add(endBox); adminwidgets.add(endLabel);
		adminwidgets.add(wwsELabel); adminwidgets.add(wwsBox);
		pointsPan.add(timeLabel); pointsPan.add(newEventButton); pointsPan.add(prevEventButton); pointsPan.add(updateButton);
		pointsPan.add(startLabel); pointsPan.add(startBox); pointsPan.add(endLabel); pointsPan.add(endBox); pointsPan.add(wwsLabel);
		pointsPan.add(wwsELabel); pointsPan.add(wwsBox);

		dpan.addNorth(pointsPan, 3);

		if(evt.game.equals("") || evt.poolid == 3 || evt.poolid == 4 || evt.poolid == 8 || evt.creator > 0) dpan.setWidgetSize(pointsPan, 0);

		newEventButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				pointsevent tpe = new pointsevent();
				tpe.eid = evt.eid;
				tpe.encounter = "Enter";
				Date dt = new Date();
				int chour = dt.getHours();
				if(chour + rp.timeos < 0) chour = (24 + chour + rp.timeos)%24;
				else chour = (chour + rp.timeos) % 24;
				tpe.ts =new NCDate(evt.starttime.year+1900,evt.starttime.month,evt.starttime.day,chour,dt.getMinutes());
				lastts = tpe.ts;
				for(pointsevent p : pointslist){
					lootRow tlr = (lootRow) rl.get(p);
					tlr.mrow++;
				}
				pointslist.add(tpe);
				lootRow tlr = new lootRow(tpe);
				tlr.UpdateFields();
				rl.put(tpe,tlr);
				tlr.mrow = -2;
				rl.get(tpe).DrawRow(pointsdisplay,0,"");
			}
		});

		prevEventButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				if(lastboss == null || lastboss.equalsIgnoreCase("") || lastts == null){
					newEventButton.click();
					return;
				}
				pointsevent tpe = new pointsevent();
				tpe.eid = evt.eid;
				tpe.encounter = new String(lastboss);
				tpe.ts = new NCDate(lastts.year+1900,lastts.month,lastts.day,lastts.hour,lastts.minute);
				for(pointsevent p : pointslist){
					lootRow tlr = (lootRow) rl.get(p);
					tlr.mrow++;
				}
				pointslist.add(tpe);
				lootRow tlr = new lootRow(tpe);
				tlr.UpdateFields();
				rl.put(tpe,tlr);
				tlr.mrow = -2;
				rl.get(tpe).DrawRow(pointsdisplay,0,"");
			}
		});

		updateButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				ArrayList<pointsevent> validlist = new ArrayList<pointsevent>();
				if(!startBox.getText().equals("")){
					if(evt.actstart == null){
						evt.actstart = new NCDate(evt.starttime);
					}
					evt.actstart.hour = Integer.parseInt(startBox.getText().split(":")[0]);
					evt.actstart.minute = Integer.parseInt(startBox.getText().split(":")[1]);
					evt.actstart.ms = evt.actstart.minstamp(evt.actstart);
				}
				else evt.actstart = null;
				if(!endBox.getText().equals("")){
					if(evt.actend == null){
						evt.actend = new NCDate(evt.actstart);
					}
					evt.actend.setTime(Integer.parseInt(endBox.getText().split(":")[0]), Integer.parseInt(endBox.getText().split(":")[1]));
				}
				else evt.actend = null;
				if(!wwsBox.getText().equals("")){
					evt.wws = wwsBox.getText();
				}

				for(pointsevent p: pointslist){
					lootRow tlr = (lootRow) rl.get(p);
					if(tlr != null){
						if(!tlr.changed) continue; 
						tlr.SaveFields();
					}
					if(ValSend(p)){
						//					
						if(p.encounter.equalsIgnoreCase("Exit")){
							NCDate rs=null; NCDate cs = null;
							for(pointsevent z : pointslist){
								if(z.encounter.equalsIgnoreCase("Enter") && z.charname.equalsIgnoreCase(p.charname)){
									if((cs==null || z.ts.compareTo(cs) > 0) && p.ts.compareTo(z.ts) >= 0) cs = z.ts;
								}
								else if(z.encounter.equalsIgnoreCase("Raid Start")){
									rs = z.ts;
								}
							}
							if(cs != null) rs = cs;
							else rs = evt.actstart;
							if(rs != null) p.name = Double.toString(tsDiff(p.ts,rs));
						}
					}
					validlist.add(p);
				}
				AsyncCallback<ArrayList<pointsevent>> updateCallback = new AsyncCallback<ArrayList<pointsevent>>(){

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(ArrayList<pointsevent> result) {
						RePoints();
						pointslist.addAll(result);
						Collections.sort(pointslist,peComp);
						Collections.reverse(pointslist);
						rl.clear();
						for(pointsevent p: pointslist){
							rl.put(p, new lootRow(p));
						}
						DrawPointsList();
						GetChars();
						updateButton.setEnabled(true);
					}

				};
				updateButton.setEnabled(false);
				rp.rpsvc.UpdateLoot(evt, validlist, updateCallback);
			}

		});

		ScrollPanel ptPan = new ScrollPanel();
		pointsdisplay = new FlexTable();
		pointsdisplay.setStyleName("cw-FlexTable2");
		ptPan.add(pointsdisplay);
		dpan.add(ptPan);

		//		chardisplay.addClickHandler(new ClickHandler(){
		//
		//			@Override
		//			public void onClick(ClickEvent event) {
		//				int cRow = chardisplay.getCellForEvent(event).getRowIndex();
		//				int cCol = chardisplay.getCellForEvent(event).getCellIndex();
		//				String rc = cRow + "," + cCol;
		//				if(cmap.get(rc) != null) rp.ViewChar(cmap.get(rc));
		////				if(!viewSlot){
		////				character c = null;
		////				int rc = -1;
		////				for(int i = 0; i < charlist.size(); i++){
		////					if(charlist.get(i).slot.equals("slotted")) rc++;
		////					if(rc == (cCol*5 + cRow)) c = charlist.get(i);
		////				}
		////				if(c == null) return;;
		////				rp.ViewChar(c);
		////				}
		//				}
		//			
		//		});

		chardisplay.addMouseDownHandler(new MouseDownHandler(){

			@Override
			public void onMouseDown(MouseDownEvent event) {
				int cRow = chardisplay.getCellForEvent(event).getRowIndex();
				int cCol = chardisplay.getCellForEvent(event).getCellIndex();
				String rc = cRow + "," + cCol;

				if(event.getNativeEvent().getButton() == NativeEvent.BUTTON_LEFT){
					if(cmap.get(rc) != null && !evt.game.equals("")) rp.ViewChar(cmap.get(rc),evt.poolid);
				}
				else if(event.getNativeEvent().getButton() == NativeEvent.BUTTON_RIGHT){
					event.preventDefault();
					event.stopPropagation();
					if(cmap.get(rc) == null || !editButton.getValue()) return;
					PointsPopup ppop = new PointsPopup(mpp,cmap.get(rc));
					ppop.setPopupPosition(event.getClientX(), event.getClientY());
					ppop.show();


				}
			}

		});



		charCallback = new AsyncCallback<ArrayList<character>>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(ArrayList<character> result) {
				charlist.clear();
				charlist.addAll(result);
				oracle.clear();
				for(character c : result){
					if(c.uid == rp.uid) signupButton.setText("Sign Up/Cancel");
					oracle.add(c.name);
				}
				DrawCharList();
				GetMyChar();
			}

		};

		bossCallback = new AsyncCallback<HashMap<String,ArrayList<String[]>>>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(HashMap<String, ArrayList<String[]>> result) {
				bids = new ArrayList<String>();
				String[] blist = result.get("ruleset").get(0);
				for(int z = 4; z < blist.length; z++){
					bids.add(blist[z].split(":")[0]);
				}
				result.remove("ruleset");
				bossloot = result;				
				bosssort.addAll(bossloot.keySet());
				Collections.sort(bosssort);
			}

		};

		if(!evt.publish || evt.game.equals("") || evt.poolid == 3 || evt.poolid == 4 || evt.poolid == 8 || evt.game.equals("SWTOR")){
			viewSlot = true;
			viewButton.setText("Points View");
		}

		if(evt.game.equals("") || evt.poolid == 3 || evt.poolid == 4 || evt.poolid == 8){
			viewButton.setVisible(false);
		}

		if(evt.creator > 0){
			viewButton.setVisible(false);
			viewSlot = true;
		}

		for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(false);

		//		if(rp.auth == RaidPoints.AuthType.cl){
		//			AsyncCallback<Boolean> clCallback = new AsyncCallback<Boolean>(){
		//
		//				@Override
		//				public void onFailure(Throwable caught) {
		//					// TODO Auto-generated method stub
		//					
		//				}
		//
		//				@Override
		//				public void onSuccess(Boolean result) {
		//					isCL= result;
		//					rp.rpsvc.GetBosses(evt,bossCallback);
		//					if(result) HandleAuthChange(RaidPoints.AuthType.admin);
		//					else HandleAuthChange(rp.auth);
		//					Refresh();
		//				}
		//				
		//			};
		//			rp.rpsvc.CharterPerm(evt, clCallback);
		//		}
		//		else{
		//		rp.rpsvc.GetBosses(evt,bossCallback);
		//		HandleAuthChange(rp.auth);
		//		Refresh();
		//		}

		if(evt.creator == 0 && !evt.game.equals("")) rp.rpsvc.GetBosses(evt,bossCallback);
		HandleAuthChange(rp.auth);
		Refresh();

		GetChat();

		Timer refreshTimer = new Timer(){

			@Override
			public void run() {
				if(!editButton.getValue()) Refresh();				
			}

		};
		refreshTimer.scheduleRepeating(120000);
	}

	public void Refresh(){
		if(!evt.game.equals("")){
			GetChars();
			if(evt.creator == 0) GetLoot();
			if(evt.actstart != null){
				timeLabel.setText("Raid Start: " + evt.actstart.getTime());  
			}
			if(evt.actend != null){
				timeLabel.setText(timeLabel.getText() + " Raid End: " + evt.actend.getTime());
			}
			if(!evt.wws.equals("")){
				if(evt.wws.startsWith("rk")){
					wwsLabel.setHTML("&nbsp&nbsp&nbsp<a href=\"http://memoriesofxendor.com/parser/raiddata.aspx\" target=_blank>Raid Key:</a> " + evt.wws.substring(2));
				}
				else wwsLabel.setHTML("&nbsp&nbsp&nbsp<a href=\"" + evt.wws + "\" target=_blank>Raid Stats</a>");
			}
		}
		if(!editButton.getValue()) GetEvent();
	}

	public void GetChat(){
		if(evt.game.equals("")) chatArea.setHTML("Welcome to " + evt.note.split(":;:")[0] + " - " + evt.note.split(":;:")[1] + "<hr/>");
		else if(evt.creator == 0) chatArea.setHTML("Welcome to <a href=\"javascript:void(0)\" onclick=\"showgroupinfo(" + evt.gid + ");\">" + evt.group + "'s</a> " + evt.dest + " " + evt.note + " (eid " + evt.eid + ")<br>" + "Sched. Start: " + evt.starttime.getFullDate(rp.mil) + " Sched. End: " + evt.endtime.getFullDate(rp.mil) + "<br>Use /roll or /random to generate random integers<hr/>");
		else chatArea.setHTML("Welcome to "+ evt.game + " - " + evt.dest + " - " + evt.note + " (eid " + evt.eid + ")<br>" + "Sched. Start: " + evt.starttime.getFullDate(rp.mil) + " Sched. End: " + evt.endtime.getFullDate(rp.mil) + "<br>Use /roll or /random to generate random integers<hr/>");

		AsyncCallback<ArrayList<String>> chatCallback = new AsyncCallback<ArrayList<String>>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(ArrayList<String> result) {
				for(int i = 0; i < result.size(); i++){
					String s = result.get(i);
					if(i == 0) rp.mpointer = Integer.parseInt(result.get(0));
					else chatArea.setHTML(chatArea.getHTML() + "<br>" + s);
				}
				chatScroll.scrollToBottom();
			}

		};
		rp.rpsvc.GetChatMessages(evt, chatCallback);			
	}

	public boolean ValSend(pointsevent pevt){
		if(pevt.encounter.equalsIgnoreCase("")) return false;
		else if (pevt.ts == null) return false;
		else if(pevt.encounter.equalsIgnoreCase("Raid Start") || pevt.encounter.equalsIgnoreCase("Raid End")){
			return true;
		}
		else{
			if(pevt.charname.matches("[a-zA-Z0-9]+")) return true;
			else return false;
		}
	}

	public void GetChars(){
		rp.rpsvc.GetCharacters(evt, charCallback);
	}

	public void DrawCharList(){
		chardisplay.clear();
		int rowc = chardisplay.getRowCount();
		for(int i = 0; i < rowc; i++) {
			chardisplay.removeRow(0);
		}

		cmap.clear();
		if(viewSlot){
			chardisplay.setStyleName("cw-FlexTableP");

			//chardisplay.setBorderWidth(1);

			if(roles.size() == 0){
				GetRoles();
				return;
			}
			int[] crow = new int[roles.size()]; 
			for(int i = 0; i < roles.size(); i++){
				chardisplay.setWidget(0, i, new HTML("<font size=\"3\">" + roles.get(i) + "</font>"));
				crow[i] = 2;
				if(roles.size() > 1) chardisplay.getColumnFormatter().setWidth(i, "110px");
				else chardisplay.getColumnFormatter().setWidth(i, "170px");
				//chardisplay.getCellFormatter().setWidth(0, i, "110px");
				chardisplay.getCellFormatter().setStyleName(0,i,"cw-FlexTableHeader");
			}
			if(!evt.publish){
				chardisplay.setWidget(1,0,new HTML("<b>Signed Up</b>"));
			}
			else chardisplay.setWidget(1,0,new HTML("<b>Slotted</b>"));
			chardisplay.getFlexCellFormatter().setColSpan(1, 0, roles.size());
			chardisplay.getCellFormatter().setStyleName(1, 0, "cw-FlexTableHeader");
			int maxrow = 0;
			for(int i = 0; i < charlist.size(); i++){
				character c = charlist.get(i);
				if(!evt.publish && c.canceled) continue;
				if(evt.publish && !c.slot.equals("slotted")) continue;
				int col = 0;
				if(c.prole == null || c.prole.equals("")) {

				}
				else{
					col = evt.publish ? rolemap.get(c.slotrole) : rolemap.get(c.prole);
				}
				if(evt.game.equals("World of Warcraft")){
					chardisplay.setWidget(crow[col], col, new HTML("<a href=\"http://us.battle.net/wow/en/character/silver-hand/" + c.name + "/advanced\" target=_blank><img src=\"cicons/" + (c.Class == null ? "mage" : c.Class.toLowerCase().replace(" ", "") ) + ".png\" width=\"16\" height=\"16\"></a>" +
							c.name + ((c.uid == evt.creator && c.uid > 0) ? " (Event Creator)" : "")));
				}
				else if(evt.game.equals("SWTOR") || evt.game.equals("Rift")){
					chardisplay.setWidget(crow[col], col, new HTML("<img src=\"cicons/" + RaidPoints.GetCicon(c) + ".png\" width=\"16\" height=\"16\">" +
							c.name + ((c.uid == evt.creator && c.uid > 0) ? " (Event Creator)" : "")));
				}
				else{
					chardisplay.setWidget(crow[col], col, new HTML(c.name + ((c.uid == evt.creator && c.uid > 0) ? " (Event Creator)" : "") + (!c.note.equals("") ? "<br>" + c.note : "")));
				}
				if(charlist.get(i).Class != null){
					//chardisplay.getCellFormatter().setStyleName(crow[col], col, c.Class.toLowerCase().replace(" ", ""));
					chardisplay.getCellFormatter().setStyleName(crow[col], col, RaidPoints.GetCicon(c));
				}
				if(roles.size() == 1){
					chardisplay.getCellFormatter().setStyleName(crow[col], col, "ceventchar");
				}
				if(c.canceled){
					chardisplay.getCellFormatter().addStyleName(crow[col], col, "canceled");
				}
				cmap.put(crow[col] + "," + col, c);
				if(crow[col] > maxrow) maxrow = crow[col];
				crow[col]++;
			}
			if(evt.publish && evt.split <= 0){
				for(int i = 0; i < crow.length; i++) crow[i] = maxrow + 2;
				chardisplay.setWidget(++maxrow,0,new HTML("<b>Stand-by</b>"));
				chardisplay.getFlexCellFormatter().setColSpan(maxrow, 0, roles.size());
				chardisplay.getCellFormatter().setStyleName(maxrow, 0, "cw-FlexTableHeader");
				for(int i = 0; i < charlist.size(); i++){
					character c = charlist.get(i);
					if(c.slot.equals("slotted") || c.canceled) continue;
					if(evt.split < 0 && c.subraid > 0) continue;
					int col = 0;
					if(c.prole == null || c.prole.equals("")) {

					}
					else{
						col = evt.publish ? rolemap.get(c.slotrole) : rolemap.get(c.prole);
					}
					if(evt.game.equals("World of Warcraft")){
						chardisplay.setWidget(crow[col], col, new HTML("<a href=\"http://us.battle.net/wow/en/character/silver-hand/" + c.name + "/advanced\" target=_blank><img src=\"cicons/" + (c.Class == null ? "mage" : c.Class.toLowerCase().replace(" ", "") ) + ".png\" width=\"16\" height=\"16\"></a>" +
								c.name + ((c.uid == evt.creator && c.uid > 0) ? " (Event Creator)" : "")));
					}
					else if(evt.game.equals("SWTOR") || evt.game.equals("Rift")){
						chardisplay.setWidget(crow[col], col, new HTML("<img src=\"cicons/" + RaidPoints.GetCicon(c) + ".png\" width=\"16\" height=\"16\">" +
								c.name + ((c.uid == evt.creator && c.uid > 0) ? " (Event Creator)" : "")));
					}
					else{
						chardisplay.setWidget(crow[col], col, new HTML(c.name + ((c.uid == evt.creator && c.uid > 0) ? " (Event Creator)" : "") + (!c.note.equals("") ? "<br>" + c.note : "")));
					}
					if(charlist.get(i).Class != null && evt.creator == 0){
						//	chardisplay.getCellFormatter().setStyleName(crow[col], col, c.Class.toLowerCase().replace(" ", ""));
						chardisplay.getCellFormatter().setStyleName(crow[col], col, RaidPoints.GetCicon(c));
					}
					if(c.canceled){
						chardisplay.getCellFormatter().addStyleName(crow[col], col, "canceled");
					}
					cmap.put(crow[col] + "," + col, c);
					if(crow[col] > maxrow) maxrow = crow[col];
					crow[col]++;
				}
			}


		}
		else{
			chardisplay.setStyleName("cw-FlexTable");
			int ri = 0;
			for(int i = 0; i < charlist.size(); i++){
				if(!charlist.get(i).slot.equals("slotted")) continue;
				chardisplay.setWidget(ri%5, ri/5, new HTML("<font size=\"3\">" + charlist.get(i).name + "<br>" + round(charlist.get(i).points) + "</font>"));
				if(charlist.get(i).Class != null){
					//chardisplay.getCellFormatter().setStyleName(ri%5, ri/5, charlist.get(i).Class.toLowerCase().replace(" ", ""));
					chardisplay.getCellFormatter().setStyleName(ri%5, ri/5, RaidPoints.GetCicon(charlist.get(i)));
				}
				cmap.put((ri%5) + "," + (ri/5),charlist.get(i));
				ri++;
			}
		}

	}

	//	public void DrawPointsListNE(){
	//		pointsdisplay.clear();
	//		int i = 0;
	//		for(pointsevent p : pointslist){
	//			lootRowNE trow = (lootRowNE) rl.get(p);
	//			trow.UpdateFields();
	//			trow.DrawRow(pointsdisplay, i);
	//			i++;
	//		}
	//	}

	public void DrawPointsList(){
		pointsdisplay.clear();
		int rowc = pointsdisplay.getRowCount();
		for(int i = 0; i < rowc; i++) {
			pointsdisplay.removeRow(0);
		}
		int i = 0;
		//Collections.sort(pointslist,peComp);
		//Collections.reverse(pointslist);
		String last = "";
		currcolor = false; 
		for(pointsevent p : pointslist){
			pointsrow trow = rl.get(p);
			if(trow == null) continue;
			trow.UpdateFields();
			trow.DrawRow(pointsdisplay, i,last);
			last = p.encounter;
			i++;
		}
	}


	public interface pointsrow{
		void UpdateFields();
		void DrawRow(FlexTable t, int row, String last);
	}

	public class lootRow implements pointsrow{
		public pointsevent myp;
		public TextBox timeBox;
		public ListBox eventBox;
		public SuggestBox charBox;
		public ListBox nameBox;
		public ListBox changeTypeBox;
		public int mrow;
		boolean changed;
		FlexTable mt;

		lootRow(pointsevent p){
			myp = p;
			mrow = -1;
			timeBox = new TextBox();
			timeBox.setMaxLength(5); timeBox.setWidth("55px");
			eventBox = new ListBox();
			eventBox.addItem("Cancel");
			//eventBox.addItem("Raid Start");
			//eventBox.addItem("Raid End");
			eventBox.addItem("Enter");
			eventBox.addItem("Exit");
			for(String boss : bosssort) eventBox.addItem(boss);
			charBox = new SuggestBox(oracle);
			nameBox = new ListBox();
			changed = !(p.pid > 0);
			changeTypeBox = new ListBox();
			//changeTypeBox.addItem("Shroud"); changeTypeBox.addItem("Shroud->Standard"); changeTypeBox.addItem("Standard"); changeTypeBox.addItem("Save");
			for(String s : bids) changeTypeBox.addItem(s);
			changeTypeBox.addItem("DE");
			eventBox.addChangeHandler(new ChangeHandler(){
				@Override
				public void onChange(ChangeEvent event) {
					changed = true;
					SaveFields();
					if(eventBox.getSelectedIndex() > 2){
						if(bossloot.get(eventBox.getItemText(eventBox.getSelectedIndex())) != null){
							nameBox.clear();
							for(String[] ln : bossloot.get(eventBox.getItemText(eventBox.getSelectedIndex()))) nameBox.addItem(ln[0]);
						}

					}
					DrawRow(mt,mrow,"");
				}
			});
			changeTypeBox.addChangeHandler(new ChangeHandler(){
				@Override
				public void onChange(ChangeEvent event) {
					changed = true;
					SaveFields();
					DrawRow(mt,mrow,"");
				}
			});
			timeBox.addChangeHandler(new ChangeHandler(){

				@Override
				public void onChange(ChangeEvent event) {
					changed = true;
				}

			});
			nameBox.addChangeHandler(new ChangeHandler(){

				@Override
				public void onChange(ChangeEvent event) {
					changed = true;
				}

			});
			charBox.getTextBox().addChangeHandler(new ChangeHandler(){

				@Override
				public void onChange(ChangeEvent event) {
					changed = true;
				}

			});

		}

		public void UpdateFields() {
			timeBox.setText(myp.ts.getTime());
			if(eventBox.getSelectedIndex() >= 0){
				for(int i = 0; i < eventBox.getItemCount(); i++) {
					if(eventBox.getItemText(i).equalsIgnoreCase(myp.encounter))eventBox.setSelectedIndex(i);
				}
			}
			if(eventBox.getSelectedIndex() > 2){
				if(bossloot.get(eventBox.getItemText(eventBox.getSelectedIndex())) != null){
					nameBox.clear();
					for(String[] ln : bossloot.get(eventBox.getItemText(eventBox.getSelectedIndex()))) nameBox.addItem(ln[0]);
				}

			}
			charBox.setText(myp.charname);
			if(nameBox.getSelectedIndex() >= 0){
				for(int i = 0; i < nameBox.getItemCount(); i++) {
					if(nameBox.getItemText(i).equalsIgnoreCase(myp.name)) nameBox.setSelectedIndex(i);
				}
			}
			if(changeTypeBox.getSelectedIndex() >= 0){
				for(int i = 0; i < changeTypeBox.getItemCount(); i++) {
					if(changeTypeBox.getItemText(i).equalsIgnoreCase(myp.changetype)) changeTypeBox.setSelectedIndex(i);
				}
			}
		}

		public void SaveFields(){
			//	GWT.log(timeBox.getText());
			if(timeBox.getText().matches("[0-2]{0,1}[0-9]{0,1}[:]{0,1}[0-5]{0,1}[0-9]{0,1}")){
				if(myp.ts == null){
					//Date dt = new Date();
					myp.ts = new NCDate(evt.starttime);
				}
				myp.ts.setTime(Integer.parseInt(timeBox.getText().split(":")[0]), Integer.parseInt(timeBox.getText().split(":")[1]));
			}
			else myp.ts = null;
			if(eventBox.getSelectedIndex() >= 0) myp.encounter = eventBox.getItemText(eventBox.getSelectedIndex());
			myp.charname = charBox.getText();
			if(nameBox.getSelectedIndex() >= 0) myp.name = nameBox.getItemText(nameBox.getSelectedIndex());
			if(bossloot.get(eventBox.getItemText(eventBox.getSelectedIndex())) != null){
				for(String[] ln : bossloot.get(eventBox.getItemText(eventBox.getSelectedIndex()))){
					if(ln[0].equals(myp.name)){
						myp.lid = Integer.parseInt(ln[1]);
						break;
					}
				}
			}
			if(changeTypeBox.getSelectedIndex() >= 0) myp.changetype = changeTypeBox.getItemText(changeTypeBox.getSelectedIndex());
			lastboss = myp.encounter;
			//lastts = myp.ts;
		}

		public void DrawRow(FlexTable t, int row, String last) {
			mt = t;
			if(mrow == -2) t.insertRow(0);
			else if(mrow != -1){ t.removeRow(row);
			t.insertRow(mrow);
			}
			mrow = row;
			t.setWidget(row, 0, timeBox);
			t.setWidget(row, 1, eventBox);
			if(myp.encounter.equalsIgnoreCase("Raid Start") || myp.encounter.equalsIgnoreCase("Raid End")){
				t.getFlexCellFormatter().setColSpan(row, 1, 4);
			}
			else if(myp.encounter.equalsIgnoreCase("Enter") || myp.encounter.equalsIgnoreCase("Exit")){
				t.setWidget(row,2,charBox);
				t.getFlexCellFormatter().setColSpan(row, 2, 3);
			}
			else{
				t.setWidget(row, 2, nameBox);
				t.setWidget(row, 3, changeTypeBox);
				if(myp.changetype.equalsIgnoreCase("DE")){
					t.getFlexCellFormatter().setColSpan(row,2,2);
				}
				else t.setWidget(row, 4, charBox);
			}
		}

	}

	public class lootRowNE implements pointsrow{
		public pointsevent myp;
		public Label timeLabel;
		public Label eventLabel;
		public Label charLabel;
		public Label nameLabel;
		public Label changeTypeLabel;
		public Label costLabel;
		public HTML nameHTML;

		lootRowNE(pointsevent p){
			myp = p;
			timeLabel = new Label();
			eventLabel = new Label();
			charLabel = new Label();
			nameLabel = new Label();
			changeTypeLabel = new Label();
			costLabel = new Label();
			nameHTML = new HTML();
		}

		public void UpdateFields(){
			timeLabel.setText(myp.ts.getTime(rp.mil));
			eventLabel.setText(myp.encounter);
			charLabel.setText(myp.charname);
			if(!myp.wowid.equals("")){
				if(evt.game.equals("World of Warcraft")) nameHTML.setHTML("<a href=\"#\" rel=\"item=" + myp.wowid + "\">" + myp.name + "</a>");
				else if(evt.game.equals("Rift")) nameHTML.setHTML("<a href=\"http://rift.magelo.com/en/item/" + myp.wowid + "\">" + myp.name + "</a>");
				else nameHTML.setHTML(myp.name);
			}
			else nameHTML.setHTML(myp.name);
			changeTypeLabel.setText(myp.changetype);
			costLabel.setText(Double.toString(myp.change));
		};
		public void DrawRow(FlexTable t,int row,String last){
			t.setWidget(row, 0, timeLabel);
			t.setWidget(row, 1, eventLabel);
			if(myp.encounter.equalsIgnoreCase("Raid Start") || myp.encounter.equalsIgnoreCase("Raid End")){
				t.getFlexCellFormatter().setColSpan(row, 1, 5);
			}
			else if(myp.encounter.equalsIgnoreCase("Enter") || myp.encounter.equalsIgnoreCase("Exit")){
				t.setWidget(row,2,charLabel);
				t.getFlexCellFormatter().setColSpan(row, 2, 4);	
			}
			else{
				t.setWidget(row, 2, nameHTML);
				t.setWidget(row, 3, charLabel);
				t.setWidget(row, 4, changeTypeLabel);
				t.setWidget(row, 5, costLabel);
			}
			if(!last.equals(myp.encounter)){
				if(!((myp.encounter.equals("Exit") || myp.encounter.equals("Enter")) && (last.equals("Exit") || last.equals("Enter")))){
					currcolor = !currcolor;
				}
			}
			t.getRowFormatter().addStyleName(row, currcolor ? "brow1" : "brow2");
		}
	}

	public void GetEvent(){
		AsyncCallback<event> eventCallback = new AsyncCallback<event>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(event result) {
				if(result != null){
					evt = result;
					if(evt.actstart != null){
						timeLabel.setText("Raid Start: " + evt.actstart.getTime());  
					}
					if(evt.actend != null){
						timeLabel.setText(timeLabel.getText() + " Raid End: " + evt.actend.getTime());
					}
					if(!evt.wws.equals("")){
						if(evt.wws.startsWith("rk")){
							wwsLabel.setHTML("&nbsp&nbsp&nbsp<a href=\"http://memoriesofxendor.com/parser/raiddata.aspx\" target=_blank>Raid Key:</a> " + evt.wws.substring(2));
						}
						else wwsLabel.setHTML("&nbsp&nbsp&nbsp<a href=\"" + evt.wws + "\" target=_blank>Raid Stats</a>");
					}
				}
			}

		};
		rp.rpsvc.GetEvent(evt.eid, eventCallback);
	}

	public void GetLoot(){
		AsyncCallback<ArrayList<pointsevent>> lootCallback = new AsyncCallback<ArrayList<pointsevent>>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(ArrayList<pointsevent> result) {
				RePoints();
				pointslist.addAll(result);
				Collections.sort(pointslist,peComp);
				Collections.reverse(pointslist);
				rl.clear();
				for(pointsevent p: pointslist){
					rl.put(p, new lootRowNE(p));
				}
				DrawPointsList();
			}

		};
		rp.rpsvc.GetLoot(evt, lootCallback);
	}

	public void RePoints(){
		pointslist.clear();
		if(evt.actstart != null) startBox.setText(evt.actstart.getTime());
		if(evt.actend != null) endBox.setText(evt.actend.getTime());
		if(evt.wws != null) wwsBox.setText(evt.wws);
		//		if(evt.actstart != null){
		//			pointsevent ase = new pointsevent();
		//			ase.encounter = "Raid Start";
		//			ase.ts = evt.actstart;
		//			pointslist.add(ase);
		//		}
		//		if(evt.actend != null){
		//			pointsevent ase = new pointsevent();
		//			ase.encounter = "Raid End";
		//			ase.ts = evt.actend;
		//			pointslist.add(ase);
		//		}
	}


	public void HandleAuthChange(RaidPoints.AuthType atype){
		//	if(atype==lastatype) return;
		//		int cols = lootTable.getColumnCount();
		//		for(int i = 0; i < cols; i++){
		//			lootTable.removeColumn(0);
		//		}
		if(evt.creator > 0 && evt.creator == rp.uid) atype = RaidPoints.AuthType.creator; 
		switch(atype){
		case admin:
			editButton.setVisible(true);
			if(evt.split <= 0) slotButton.setVisible(true);
			else slotButton.setVisible(false);
			signupButton.setVisible(true);
			modButton.setVisible(true);
			chatPanel.setVisible(true);
			//		for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(true);
			//			if(lootTable == null) break;
			//			lootTable.addColumn(timeCol,"Time");
			//			lootTable.addColumn(nameCol,"Name");
			//			lootTable.addColumn(encounterCol,"Encounter");
			break;
		case cl:
			signupButton.setVisible(true);
			if(evt.split <= 0) slotButton.setVisible(true);
			else slotButton.setVisible(false);
			modButton.setVisible(false);
			chatPanel.setVisible(true);

			AsyncCallback<Boolean> clCallback = new AsyncCallback<Boolean>(){

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onSuccess(Boolean result) {
					isCL= result;
					if(result){
						editButton.setVisible(true);
						if(evt.split <= 0) slotButton.setVisible(true);
						else slotButton.setVisible(false);
						signupButton.setVisible(true);
						modButton.setVisible(true);
						chatPanel.setVisible(true);	
					}

				}

			};
			rp.rpsvc.CharterPerm(evt, clCallback);

			break;
		case creator:
			isCL = true;
			editButton.setVisible(true);
			signupButton.setVisible(true);
			slotButton.setVisible(true);
			modButton.setVisible(true);
			chatPanel.setVisible(true);
			break;
		case user:
			signupButton.setVisible(true);
			if(evt.split <= 0) slotButton.setVisible(true);
			else slotButton.setVisible(false);
			modButton.setVisible(false);
			chatPanel.setVisible(true);
			break;
		default:
			if(editButton.getValue()){
				editButton.setValue(false);
				GetLoot();
			}
			timeLabel.setVisible(true);
			wwsLabel.setVisible(true);
			refreshButton.setVisible(true);
			signupButton.setVisible(false);
			modButton.setVisible(false);
			chatPanel.setVisible(false);
			if(evt.split <= 0) slotButton.setVisible(true);
			else slotButton.setVisible(false);
			//	dpan.setWidgetSize(pointsPan, 0);
			editButton.setVisible(false);
			for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(false);
			//	for(int i = 0; i < adminwidgets.size(); i++) adminwidgets.get(i).setVisible(false);
			//			if(lootTable == null) break;
			//			lootTable.addColumn(timeColNE,"Time");
			//			lootTable.addColumn(nameColNE,"Name");
			break;
		}
		lastatype = atype;
		if(evt.creator > 0) editButton.setVisible(false);
		if(evt.game.equals("")){
			editButton.setVisible(false);
			signupButton.setVisible(false);
			slotButton.setVisible(false);
		}
		//	Window.alert(Integer.toString(lootTable.getColumnCount()));
	}

	public void GetMyChar(){
		if(rp.uid == -1) return;
		for(character c : charlist){
			if(c.uid == rp.uid && c.uid != -1){
				mychar = c.name;
				if(c.slot.equals("slotted")) break;
			}
		}
	}

	public void AddMessage(String message){
		chatArea.setHTML(chatArea.getHTML() + "<br>" + message);
		chatScroll.scrollToBottom();
	}

	public void GetRoles(){
		AsyncCallback<String> rollCallback = new AsyncCallback<String>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(String result) {
				String[] split = result.split(",");
				roles.clear();
				rolemap.clear();
				for(int i = 0; i < split.length; i++){
					roles.add(split[i]);
					rolemap.put(split[i], i);
				}
				DrawCharList();
			}

		};
		rp.rpsvc.GetRoles(evt, rollCallback);
	}

	public static double tsDiff(NCDate t1, NCDate t2){
		double diff = t1.diff(t2);
		return round(diff / (60.0));
	}

	public static double round(double in){
		return Math.round(in*100)/100.00d;
	}

	public class MyFlexTable extends FlexTable implements HasMouseDownHandlers {

		public MyFlexTable(){
			sinkEvents(Event.ONCONTEXTMENU);
		}

		public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) {
			return addDomHandler(handler, MouseDownEvent.getType());
		}

		@Override
		public void onBrowserEvent(Event theEvent) {
			int anEventType = DOM.eventGetType(theEvent);
			if(anEventType == Event.ONCONTEXTMENU) {
				theEvent.stopPropagation();// This will stop the event from being propagated
				theEvent.preventDefault();
			} else {
				// other browser events
				super.onBrowserEvent(theEvent);
			}
		}


		// This useful method is taken from HTMLTable. Only the signature needs
		// to be changed, unfortunately that means copying the whole method.
		public Cell getCellForEvent(MouseEvent event) {
			//			Element td = getEventTargetCell(Event.as(event.getNativeEvent()));
			//			if (td == null) {
			//				return null;
			//			}
			//
			//			Element tr = DOM.getParent(td);
			//			Element body = DOM.getParent(tr);
			//			int row = DOM.getChildIndex(body, tr);
			//			int column = DOM.getChildIndex(tr, td);
			//			return new this.Cell(row, column);

			Element td = getEventTargetCell(Event.as(event.getNativeEvent()));
			if (td == null) {
				return null;
			}

			int row = TableRowElement.as(td.getParentElement()).getSectionRowIndex();
			int column = TableCellElement.as(td).getCellIndex();
			return new StupidCell(this,row, column);
		}
	}

	public class StupidCell extends HTMLTable.Cell{
		public StupidCell(HTMLTable htmlTable, int rowIndex, int cellIndex) {
			htmlTable.super(rowIndex, cellIndex);

		}

	}

	public class PointsPopup extends PopupPanel {
		PointsPage pp;
		character tc;
		ListBox charBox;
		SuggestBox scharBox;
		CheckBox switchBox;
		Button swapButton;
		Button leaveButton;
		MultiWordSuggestOracle oracle;
		String lastentry;
		public PointsPopup(PointsPage mpp, character mtc){
			super(true);
			pp = mpp;
			tc = mtc;
			lastentry = "";
			VerticalPanel mvpan = new VerticalPanel();
			final HorizontalPanel hpan = new HorizontalPanel();
			HorizontalPanel timepan = new HorizontalPanel();
			charBox = new ListBox();
			oracle = new MultiWordSuggestOracle();
			scharBox = new SuggestBox(oracle);
			charBox.setWidth("150px"); scharBox.setWidth("150px");
			switchBox = new CheckBox("Non-Alt");
			swapButton = new Button("Swap");
			leaveButton = new Button("Leave");
			setWidget(mvpan);
			sinkEvents(Event.ONCONTEXTMENU);

			mvpan.add(new Label("Attendance Swap: " + tc.name));
			hpan.add(charBox); hpan.add(switchBox);
			mvpan.add(hpan);

			timepan.add(swapButton); timepan.add(leaveButton);
			mvpan.add(timepan);

			switchBox.addValueChangeHandler(new ValueChangeHandler<Boolean>(){

				@Override
				public void onValueChange(ValueChangeEvent<Boolean> event) {
					if(event.getValue()){
						hpan.remove(charBox);
						hpan.insert(scharBox, 0);
					}
					else{
						hpan.remove(scharBox);
						hpan.insert(charBox, 0);
					}
				}

			});

			leaveButton.addClickHandler(new ClickHandler(){

				@Override
				public void onClick(ClickEvent event) {
					if(!pp.editButton.getValue()) {hide(); return;}
					pointsevent tpe = new pointsevent();
					tpe.eid = pp.evt.eid;
					tpe.encounter = "Exit";
					tpe.charname = tc.name;
					Date dt = new Date();
					int chour = dt.getHours();
					if(chour + rp.timeos < 0) chour = (24 + chour + rp.timeos)%24;
					else chour = (chour + rp.timeos) % 24;
					tpe.ts =new NCDate(evt.starttime.year+1900,evt.starttime.month,evt.starttime.day,chour,dt.getMinutes());
					pp.lastts = tpe.ts;
					for(pointsevent p : pp.pointslist){
						lootRow tlr = (lootRow) pp.rl.get(p);
						tlr.mrow++;
					}
					pp.pointslist.add(tpe);
					lootRow tlr = new lootRow(tpe);
					tlr.UpdateFields();
					rl.put(tpe,tlr);
					tlr.mrow = -2;
					rl.get(tpe).DrawRow(pointsdisplay,0,"");		
					hide();
				}

			});

			swapButton.addClickHandler(new ClickHandler(){

				@Override
				public void onClick(ClickEvent event) {
					if(!pp.editButton.getValue()) {hide(); return;}
					if((!switchBox.getValue() && charBox.getItemCount() == 0) || (switchBox.getValue() && scharBox.getText().length() == 0)) {hide(); return;}
					Date dt = new Date();
					int chour = dt.getHours();
					if(chour + rp.timeos < 0) chour = (24 + chour + rp.timeos)%24;
					else chour = (chour + rp.timeos) % 24;
					NCDate ts =new NCDate(evt.starttime.year+1900,evt.starttime.month,evt.starttime.day,chour,dt.getMinutes());
					pp.lastts = ts;

					pointsevent tpe = new pointsevent();
					tpe.eid = pp.evt.eid;
					tpe.encounter = "Exit";
					tpe.charname = tc.name;
					tpe.ts = ts;
					for(pointsevent p : pp.pointslist){
						lootRow tlr = (lootRow) pp.rl.get(p);
						tlr.mrow++;
					}
					pp.pointslist.add(tpe);
					lootRow tlr = new lootRow(tpe);
					tlr.UpdateFields();
					rl.put(tpe,tlr);
					tlr.mrow = -2;
					rl.get(tpe).DrawRow(pointsdisplay,0,"");

					tpe = new pointsevent();
					tpe.eid = pp.evt.eid;
					tpe.encounter = "Enter";
					tpe.charname = switchBox.getValue() ? scharBox.getText() : charBox.getItemText(charBox.getSelectedIndex()).substring(0,charBox.getItemText(charBox.getSelectedIndex()).indexOf(" "));
					tpe.ts = ts;
					for(pointsevent p : pp.pointslist){
						lootRow tlrr = (lootRow) pp.rl.get(p);
						tlrr.mrow++;
					}
					pp.pointslist.add(tpe);
					tlr = new lootRow(tpe);
					tlr.UpdateFields();
					rl.put(tpe,tlr);
					tlr.mrow = -2;
					rl.get(tpe).DrawRow(pointsdisplay,0,"");

					hide();
				}

			});

			final AsyncCallback<ArrayList<String>> searchCallback = new AsyncCallback<ArrayList<String>>(){

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onSuccess(ArrayList<String> result) {
					if(result == null) return;
					oracle.clear();
					//	GWT.log("Adding " + Integer.toString(result.size()) + " Suggestions");
					for(String s : result) oracle.add(s);
					scharBox.showSuggestionList();
				}


			};


			scharBox.getTextBox().addKeyUpHandler(new KeyUpHandler(){
				@Override
				public void onKeyUp(KeyUpEvent event) {
					if(!scharBox.getTextBox().getText().equals(lastentry)){
						lastentry = scharBox.getTextBox().getText();
						if(lastentry.length() > 1) pp.rp.rpsvc.SearchChars(lastentry, pp.evt, searchCallback);	
						else oracle.clear();
					}
				}
			});



			AsyncCallback<ArrayList<String>> charCallback = new AsyncCallback<ArrayList<String>>(){

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onSuccess(ArrayList<String> result) {
					if(result == null) return;
					charBox.clear();
					for(String s: result){
						if(!s.split(",")[0].equals(tc.name)) charBox.addItem(s.split(",")[0] + " (" + s.split(",")[1] + ")");
					}
				}

			};
			mpp.rp.rpsvc.GetAlts(tc.cid, mpp.evt, charCallback);
		}

		@Override
		public void onBrowserEvent(Event theEvent) {
			int anEventType = DOM.eventGetType(theEvent);
			if(anEventType == Event.ONCONTEXTMENU) {
				theEvent.stopPropagation();// This will stop the event from being propagated
				theEvent.preventDefault();
			} else {
				// other browser events
				super.onBrowserEvent(theEvent);
			}
		}
	}


}
